package cn.foolishbird.crow.mybatis.plus.service.impl;

import cn.foolishbird.crow.core.util.CollectionTools;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.foolishbird.crow.mybatis.plus.po.CrowPO;
import cn.foolishbird.crow.mybatis.plus.service.CrowService;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @author Eric
 * @since 2019-05-06
 */
public class CrowServiceImpl<M extends BaseMapper<E>, E extends CrowPO> extends ServiceImpl<M, E>
        implements CrowService<E> {


    @Override
    public void refreshBySet(Collection<E> entities, Supplier<Collection<E>> query) {
        // 查询数据库
        Collection<E> dbList = query.get();

        Collection<E> insertList  = entities.stream()
                .filter(e -> Objects.isNull(e.getId()))
                .collect(Collectors.toList());

        Collection<E> compareList = entities.stream()
                .filter(e -> Objects.nonNull(e.getId()))
                .collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(insertList)) {
            this.saveBatch(insertList);
        }

        Collection<E> updateList = CollectionTools.intersection(compareList, dbList, CrowPO::getId);
        if (!CollectionUtils.isEmpty(updateList)) {
            this.updateBatchById(updateList);
        }

        Collection<E> deleteList = CollectionTools.subtract(dbList, updateList, CrowPO::getId);
        if (!CollectionUtils.isEmpty(deleteList)) {
            this.removeBatchByIds(deleteList);
        }
    }
}
